// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ws

import (
	"encoding/json"
	"log"
)

// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
	// Registered clients.
	clients map[*Client]int64

	// Register requests from the clients.
	register chan *Client

	// Unregister requests from clients.
	unregister chan *Client

	// 登录消息
	login chan *Message

	// Inbound messages from the clients.
	broadcast chan *Message
}

func NewHub() *Hub {
	return &Hub{
		broadcast:  make(chan *Message),
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[*Client]int64),
		login:      make(chan *Message),
	}
}

func (h *Hub) Run() {
	for {
		select {
		case client := <-h.register: // 新的连接
			log.Println("新注册连接", client)
			h.clients[client] = 0

		case client := <-h.unregister: // 失去连接
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				log.Println("关闭连接", client)
				close(client.send)
			}

		// 连接后发的登录消息
		case message := <-h.login:
			log.Println(message)
			b, err := json.Marshal(message)
			if err != nil {
				continue
			}

			for client := range h.clients {
				select {
				case client.send <- b:
					log.Println(client)
					log.Println(message)
				default:
					close(client.send)
					delete(h.clients, client)
				}
			}

		case message := <-h.broadcast:
			for client := range h.clients {
				b, err := json.Marshal(message)
				if err != nil {
					continue
				}

				select {
				case client.send <- b:
					log.Println(client)
					log.Println(message)
				default:
					close(client.send)
					delete(h.clients, client)
				}
			}
		}
	}

}
